const {ScheduleTask} = require('@/mysql/schedule')
const {Project} = require('@/mysql/project')
const {UserProject} = require('@/mysql/user_project')
/** 查找查看项目所有任务 */
const getAllScheduleTask = async ctx => {
    // ctx.response.body = global.utils.PersonInfo
    const project_id = ctx.params.id
    const data =await ScheduleTask.getAllScheduleTasks(project_id)
    ctx.body = data
}
/** 添加任务 */
const insertScheduleTask = async ctx => {
    if (ctx.request.body) {
        //步骤——————》 表单验证，判断是否存在项目，判断该项目是不是属于用户，允许插入
        const project_id = ctx.params.id
        let {name, description, mark_date, expire_time, update_user} = ctx.request.body
        if (!project_id) return ctx.response.body = global.toJson(1, `缺少任务Id`)
        if (!name) return ctx.response.body = global.toJson(1, `缺少任务名称`)
        if (!mark_date) return ctx.response.body = global.toJson(1, `缺少日期任务日期`)
        const projects = await Project.findById(project_id);
        if (projects.length === 0) return ctx.response.body = global.toJson(1, `没有找到该项目`)
        const userInfo = await UserProject.findByProjectId(project_id)
        if(userInfo.length === 0) return ctx.response.body = global.toJson(1, `该项目没有归属人，不能进行操作`)
        if(global.utils.getUserId() !== Number(userInfo[0].user_id))  return ctx.response.body = global.toJson(1, `没有权限操作该项目`)
        const data = await ScheduleTask.insertData(project_id, name, description, mark_date, expire_time, update_user)
        if (data) {
            ctx.response.body = global.toJson(0, '添加任务成功')
        }
    }
}
// 修改任务
const updateScheduleTask = async ctx => {
    const params = ctx.request.body
    if(params) {
        let {name, description, id, update_user, expire_time, mark_date} = params
        const data = await ScheduleTask.updateData(id,name,description, update_user, expire_time, mark_date)
        if(data.length !== 0) ctx.body = global.toJson(0, `修改任务完成`)
    }
}

const removeScheduleTask = async ctx => {
    const removeId = ctx.params.id
    if(!removeId) ctx.body = global.toJson(1, `没有任务Id,无法删除`)
    const data =  await ScheduleTask.update({
        deleted: true
    },{where:{id:removeId}})
    if(data.length !== 0) ctx.body = global.toJson(0, '删除成功')
}

const updateTaskStatus = async ctx => {
    const {status, id} = ctx.request.body;
    if(!status) return ctx.body = global.toJson(1, '修改任务状态参数缺失')
    if(!id) return ctx.body = global.toJson(1, '修改任务状态Id缺失')
    await ScheduleTask.update({
        status
    }, {where: {id}})
    return ctx.body = global.toJson(0, '修改任务状态成功')
}
export {getAllScheduleTask, insertScheduleTask, updateScheduleTask, removeScheduleTask, updateTaskStatus}
